package ldh.maker.db;

import ldh.maker.util.UiUtil;
import ldh.maker.vo.TableNo;
import ldh.maker.vo.TableViewData;
import ldh.maker.vo.TreeNode;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by ldh123 on 2018/5/5.
 */
public class TableNoDb {

    public static TableNo loadData(TreeNode treeNode, String dbName) throws SQLException {
        List<TableNo> data = new ArrayList<>();
        Connection connection = UiUtil.H2CONN;
        QueryRunner queryRunner = new QueryRunner();
        String sql = "select id, db_name as dbName, content, tree_node_id as treeNodeId" +
                " from table_no where tree_node_id = ? and db_name = ?";
        ResultSetHandler<List<TableNo>> h = new BeanListHandler<>(TableNo.class);
        data = queryRunner.query(connection, sql, h, treeNode.getId(), dbName);
        return data.size() > 0 ? data.get(0) : null;
    }

    public static void save(TableNo data) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        QueryRunner queryRunner = new QueryRunner();
        String sql = "insert into table_no(db_name, content, tree_node_id) values(?, ?, ?)";
        String updateSql = "update table_no set content = ? where id = ?";

        if (data.getId() == null) {
            int i = 0;
            Object[] param = new Object[3];
            param[i++] = data.getDbName();
            param[i++] = data.getContent();
            param[i++] = data.getTreeNodeId();
            Integer id = queryRunner.insert(connection, sql, new ScalarHandler<Integer>(1), param);
            data.setId(id);
        } else {
            queryRunner.update(connection, updateSql, data.getContent(), data.getId());
        }
    }

    public static void delete(TreeNode treeNode) throws SQLException {
        Connection connection = UiUtil.H2CONN;
        QueryRunner queryRunner = new QueryRunner();
        String sql = "delete from table_no where tree_node_id = ?";
        queryRunner.update(connection, sql, treeNode.getId());
    }
}
